package com.osdp.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.osdp.auth.server.ILoginService;
import com.osdp.auth.vo.LoginModel;
import com.osdp.common.constant.CommonConstant;
import com.osdp.common.exception.PlatformException;
import com.osdp.common.http.Result;
import com.osdp.common.util.MessageUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.captcha.servlet.MicaCaptchaServlet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Api(tags="用户登录")
@RestController
//@RefreshScope
@RequestMapping("/auth/login")
public class LoginController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

//    @Autowired
//    @Qualifier("consumerTokenServices")
//    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private ILoginService loginService;

    @Autowired
    private MicaCaptchaServlet micaCaptcha;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/index")
    public String getIndex(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("micro-uc");
        log.info("{}:{}:{}", serviceInstance.getServiceId(),
                serviceInstance.getHost(),serviceInstance.getPort());
        System.out.println("ServiceId: "+ serviceInstance.getServiceId()+
                "----------host: "+serviceInstance.getHost()+"-------------port: "+serviceInstance.getPort());
        return "hello index";
    }

    /**
     * 图形验证码
     */
    @GetMapping(value = "/captcha", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public ResponseEntity<Resource> captcha(HttpServletResponse response) {
        log.info("micaCaptcha:" + micaCaptcha + ",response:" + response);
        return micaCaptcha.generate(response);
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginModel loginModel, HttpServletResponse response) {
         //验证码校验，需要为：0
         if (!loginModel.isIgnoreCaptcha()) {
             if (StringUtils.isEmpty(loginModel.getCaptcha())) {
                 return Result.fail(MessageUtil.getMessage(10117));
             }
             String vcode = loginModel.getCaptcha().trim();
             if (!micaCaptcha.validate(response, vcode)) {
                 return Result.fail(MessageUtil.getMessage(10118));
             }
         }
         if (StringUtils.isEmpty(loginModel.getUsername())) {
             return Result.fail(MessageUtil.getMessage(10119));
         }
         if (StringUtils.isEmpty(loginModel.getPassword())) {
             return Result.fail(MessageUtil.getMessage(10120));
         }
         String username = loginModel.getUsername().trim();
         String password = loginModel.getPassword().trim();
         final String tenantCode;
         final String token;
         try {
             if (loginModel.isManagePlatform()) {
                 if (!username.contains("#")) {
                     return Result.fail(MessageUtil.getMessage(10121));
                 }
                 String[] userNameWithTenantCode = username.split("#");
                 if (userNameWithTenantCode.length < 2) {
                     return Result.fail(MessageUtil.getMessage(10121));
                 }
                 tenantCode = userNameWithTenantCode[1];
                 username = userNameWithTenantCode[0];
                 token = loginService.loginWithTenant(username, password, tenantCode);
             } else {
                 token = loginService.login(username, password);
             }
         } catch (PlatformException e) {
             log.error("用户:[{}]登录失败", username, e);
             return Result.fail(e.getMessage());
         }
         Cookie cookie = new Cookie(CommonConstant.HEADER_ACCESS_TOKEN, token);
         cookie.setPath("/");
         response.addCookie(cookie);
         JSONObject obj = new JSONObject();
         obj.put("token", token);
         return Result.success(obj);
    }

    /**
     * 登出
     * @param cookieToken
     * @return
     */
    @PostMapping("/loginOut")
    public Result loginOut(@CookieValue(value = CommonConstant.HEADER_ACCESS_TOKEN,required = false) String cookieToken,
                           @RequestHeader(value = CommonConstant.HEADER_ACCESS_TOKEN,required = false) String headerToken){
        boolean ok = false;
        if(!StringUtils.isEmpty(cookieToken)){
            ok = loginService.loginOut(cookieToken);
        }else if(!StringUtils.isEmpty(headerToken)){
            ok = loginService.loginOut(headerToken);
        }
        if(!ok){
            return Result.fail(MessageUtil.getMessage(10083));
        }
        return Result.success(MessageUtil.getMessage(10082));
    }

    @PostMapping("/removeToken")
    public Result removeToken(@RequestHeader(CommonConstant.HEADER_ACCESS_TOKEN) String accessToken, HttpServletResponse response) {
        redisTemplate.delete(CommonConstant.PREFIX_USER_TOKEN + accessToken);
        return Result.success();
    }
}
